package com.nowcoder.community.util;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.logging.Logger;

@Component
public class MailClient {
    private static final org.slf4j.Logger logger = (org.slf4j.Logger) LoggerFactory.getLogger(MailClient.class);
    @Autowired
    //发件人
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;
    /**
     * 发送邮件
     * to收件人
     * subject主题
     * content内容
     */
    public void sendMail(String to,String subject,String content){
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件失败！" + e.getMessage());
        }

    }

}
